<?php
/**
 * Created by PhpStorm.
 * User: bestWky
 * Date: 15-4-14
 * Time: 下午2:39
 */


$APPID = "wx4156160c4f1640e1";
$APPSecret = "a804e0224002c0555ff2713f5b720daa";

function curl($url,$params=null,$timeout=30){
    $user_agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
    $ch = curl_init();
    if($params){
        curl_setopt($ch, CURLOPT_POST,1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
    }
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_REFERER, $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);

    $result = curl_exec($ch);
    if(curl_errno($ch)) $result = false;
//echo $result;
    curl_close($ch);
    return $result;
}


class Helper{

    private static $accessToken;
    private static $table = 'tb_token';
    private static $appid = 'wx4156160c4f1640e1';
    private static $appSecret = 'a804e0224002c0555ff2713f5b720daa';
    private static $baseUrl = 'https://api.weixin.qq.com/cgi-bin/';

    public static function CheckTokenTime($time, $delay_time){
        $total_time = time() - intval($time);
        if($total_time >= 5000){
            return true;
        }
        return false;
    }


    public static function getAccessToken_wx($db ){
        if(self::$accessToken) return self::$accessToken;
        $where = "type='WX_API_ACCESSTOKEN'";
        $savedToken = $db->get_one('id,type,token,expires', "tb_token", $where);
        if($savedToken['token'] && time() < ($savedToken['expires'] - 120)){
            return $savedToken['token'];
        }
        $appid = self::$appid;
        $appSecret = self::$appSecret;
        $result = json_decode(file_get_contents(self::$baseUrl . 'token?grant_type=client_credential&appid='.$appid.'&secret=' . $appSecret),true);
//        if($result['errcode']){
//            $_SESSION['SNS_API_ERROR'] = json_encode($result);
//            return false;
//        }

        if(!empty($result['errcode'])){
            $_SESSION['SNS_API_ERROR'] = json_encode($result);
            return false;
        }

        $arrInput = array(
            'type' => 'WX_API_ACCESSTOKEN',
            'token' => $result['access_token'],
            'expires' => $result['expires_in'] + time()
        );
        if(empty($savedToken)){
            $db->insert($arrInput, "tb_token", true);
        }else{
            $db->update($arrInput, "tb_token", $where);
        }
        self::$accessToken = $result['access_token'];
        return self::$accessToken;
    }

    public static function getJsApiTicket_wx($accessToken, $db){
        $weixin_data = $db->get_one('token_time, access_token', "weixin", "ID=2");
        if (Helper::CheckTokenTime($weixin_data['token_time'], 7000)) {
            $token_result = curl("https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken");
            $tick_data = json_decode($token_result, true);
            $ticket = $tick_data['ticket'];
            if ($ticket) {
                $data_arr = array();
                $data_arr['token_time'] = time() + 7000;
                $data_arr['access_token'] = $tick_data['ticket'];
                $res = $db->update($data_arr, "weixin", "ID=2");
            }
        } else {
            $ticket = $weixin_data->access_token;
        }

        return $ticket;
    }

    function getRandChar($length){
        $str = null;
        //$strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $strPol = "ABCDEFGHJKLMNPQRSTUVWXYZ0123456789";
        $max = strlen($strPol)-1;
        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数    }
        }
        return $str;
    }
}

//function GrabImage($url, $isget=false, $filename = "") {
//    if ($url == ""):return false;
//    endif;//如果$url地址为空，直接退出
//    //
//    $new_url = substr($url, 0, strlen($url)-1);
//    $new_url = $new_url."96";
//    if($filename == "")
//        $filename = date("dMYHis").".jpg";//用天月面时分秒来命名新的文件名
//    //如果只是得到文件名就用这个
//    if($isget){
//        return $filename;
//    }
//
//    $filename = "img_".$filename;
//    ob_start();//打开输出
//    readfile($new_url);//输出图片文件
//    $img = ob_get_contents();//得到浏览器输出
//    ob_end_clean();//清除输出并关闭
//    $size = strlen($img);//得到图片大小
//    $fp2 = @fopen($filename , "a");
//    fwrite($fp2, $img);//向当前目录写入图片文件，并重新命名
//    fclose($fp2);
//    return $filename;//返回新的文件名
//}

function GrabImage1($url, $isget=false, $filename = "") {
    if ($url == ""):return false;
    endif;//如果$url地址为空，直接退出
    //
    $new_url = substr($url, 0, strlen($url)-1);
    $new_url = $new_url."46";
    if($filename == "")
        $filename = date("dMYHis").".jpg";//用天月面时分秒来命名新的文件名
    //如果只是得到文件名就用这个
    if($isget){
        return $filename;
    }
    $filename = "img_".$filename;
    ob_start();//打开输出
    readfile($new_url);//输出图片文件
    $img = ob_get_contents();//得到浏览器输出
    ob_end_clean();//清除输出并关闭
    $size = strlen($img);//得到图片大小
    $fp2 = @fopen('pic/'.$filename , "a");
    fwrite($fp2, $img);//向当前目录写入图片文件，并重新命名
    fclose($fp2);
    return $filename;//返回新的文件名
}


function GrabImage($url, $isget=false, $filename = "") {
    if ($url == ""):return false;
    endif;//如果$url地址为空，直接退出
    //
    $new_url = substr($url, 0, strlen($url)-1);
    $new_url = $new_url."132";
    if($filename == "")
        $filename = date("dMYHis").".jpg";//用天月面时分秒来命名新的文件名
    //如果只是得到文件名就用这个
    if($isget){
        return $filename;
    }
    $file = "img_".$filename;
    $filename = "pic/img_".$filename;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    curl_setopt($ch, CURLOPT_URL, $new_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $content = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    if ($info['http_code'] != 200)
        $content = NULL;
    if($content)//保存图片到本地
        @file_put_contents ($filename, $content);
    return $file;//返回新的文件名
}